/* 
 * Copyright (c) 2008 Knightsoft
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.knightsoft.kgui;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.Timer;

/**
 * Make the dialog shake.
 * Just like "send a nude" in MSN conversation dialog
 * 
 * @version V1.0 Nov 08, 2008
 * @author Michael
 */
public class ShakeDialog extends Object {

	public static final int SHAKE_DISTANCE = 10;
	public static final double SHAKE_CYCLE = 50;
	public static final int SHAKE_DURATION = 1000;
	public static final int SHAKE_UPDATE = 5;

	private JDialog dialog;
	private Point naturalLocation;
	private long startTime;
	private Timer shakeTimer;
	// private final double HALF_PI = Math.PI / 2.0;
	private final double TWO_PI = Math.PI * 2.0;

	public ShakeDialog(JDialog d) {
		dialog = d;
	}

	public void startShake() {
		naturalLocation = dialog.getLocation();
		startTime = System.currentTimeMillis();
		shakeTimer = new Timer(SHAKE_UPDATE, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// calculate elapsed time
				long elapsed = System.currentTimeMillis() - startTime;
				// use sin to calculate an x-offset
				double waveOffset = (elapsed % SHAKE_CYCLE) / SHAKE_CYCLE;
				double angle = waveOffset * TWO_PI;

				// offset the x-location by an amount
				// proportional to the sine, up to
				// shake_distance
				int shakenX = (int) ((Math.sin(angle) * SHAKE_DISTANCE) + naturalLocation.x);
				dialog.setLocation(shakenX, naturalLocation.y);
				dialog.repaint();

				// should we stop timer?
				if (elapsed >= SHAKE_DURATION)
					stopShake();
			}
		});
		shakeTimer.start();
	}

	public void stopShake() {
		shakeTimer.stop();
		dialog.setLocation(naturalLocation);
		dialog.repaint();
	}

	// Example:
	
	 public static void main(String[] args) { 
		 JOptionPane pane = new JOptionPane("Look, I'm shaking now !!!", 
				 JOptionPane.ERROR_MESSAGE,
				 JOptionPane.OK_OPTION); 
		 JDialog d = pane.createDialog(null, "Shakin'!");
		 ShakeDialog dec = new ShakeDialog(d); 
		 d.pack(); 
		 d.setModal(false);
		 d.setVisible(true); 
		 dec.startShake();
	 }
	  
	 // wait (forever) for a non-null click and then quit while
	/*
	 if (pane.getValue() == JOptionPane.UNINITIALIZED_VALUE) { 
		 try {
			 Thread.sleep(100); 
		} catch (InterruptedException ie) { } 
		}
	 	System.exit(0); 
	 }
	 */
	 

}
